import type { DiscoveryTableListType } from "src/pages/Discovery/interface";
import { menu } from "../config";

export function discoverData(data: any) {
  const { strees, lvses, starks, manuals, urls } = data;
  const resData = { strees, lvses, starks, manuals, urls };
  const result: any = [];
  Object.keys(resData).map((item) => {
    if (data[item]) {
      const arr = data[item].map((dataItem: any) => {
        let name = menu[item];
        return {
          discoverType: item,
          data: dataItem,
          name: name,
        };
      });
      result.push(...arr);
    }
  });
  return result;
}

function uniq(arr: DiscoveryTableListType[]) {
  return arr.reduce(
    (prev: DiscoveryTableListType[], cur: DiscoveryTableListType) => {
      if (!prev.some((item: DiscoveryTableListType) => item.id === cur.id)) {
        prev.push(cur);
      }
      return prev;
    },
    []
  );
}

export function data2Discover(data: Record<string, any>[]) {
  let strees: DiscoveryTableListType[] = [],
    urls: DiscoveryTableListType[] = [],
    starks: DiscoveryTableListType[] = [],
    manuals: DiscoveryTableListType[] = [],
    lvses: DiscoveryTableListType[] = [];
  data.forEach((item) => {
    switch (item.discoverType) {
      case "stree":
        strees.push(item.data);
        break;
      case "strees":
        strees.push(item.data);
        break;
      case "基于服务树节点":
        strees.push(item.data);
        break;
      case "stark":
        starks.push(item.data);
        break;
      case "starks":
        starks.push(item.data);
        break;
      case "STARK容器":
        starks.push(item.data);
        break;
      case "url":
        urls.push(item.data);
        break;
      case "urls":
        urls.push(item.data);
        break;
      case "基于HTTP接口":
        urls.push(item.data);
        break;
      case "manual":
        manuals.push(item.data);
        break;
      case "manuals":
        manuals.push(item.data);
        break;
      case "基于手工配置":
        manuals.push(item.data);
        break;
      case "lvs":
        lvses.push(item.data);
        break;
      case "lvses":
        lvses.push(item.data);
        break;
      case "基于LVS":
        lvses.push(item.data);
        break;
      default:
        console.log("err");
    }
  });
  strees = uniq(strees);
  starks = uniq(starks);
  manuals = uniq(manuals);
  urls = uniq(urls);
  lvses = uniq(lvses);
  return { strees, starks, manuals, urls, lvses };
}
